package com.lenovo.locationmanager;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mixiaoxiao.smoothcompoundbutton.SmoothRadioGroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends CheckPermissionsActivity {
    private static final String TAG = MainActivity.class.getSimpleName();


    @BindView(R.id.et_longitude)
    EditText etLongitude;
    @BindView(R.id.et_latitude)
    EditText etLatitude;
    @BindView(R.id.rg_start)
    SmoothRadioGroup rgStartWay;
    @BindView(R.id.millisecond_between_sessions)
    EditText etIntervalTime;
    @BindView(R.id.btn_start)
    Button btnStart;
    @BindView(R.id.btn_stop)
    Button btnStop;
    @BindView(R.id.et_session_times)
    EditText etSessionTimes;
    @BindView(R.id.overtime)
    EditText etOvertime;
    @BindView(R.id.retry_times)
    EditText etRetryTimes;

    //结果布局
    @BindView(R.id.tv_longitude)
    TextView tvLongitude;
    @BindView(R.id.tv_latitude)
    TextView tvLatitude;
    @BindView(R.id.tv_altitude)
    TextView tvAltitude;
    @BindView(R.id.tv_sessionNo)
    TextView tvSessionNo;
    @BindView(R.id.tv_failureNo)
    TextView tvFailureNo;
    @BindView(R.id.tv_ttff)
    TextView tvTTFF;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_usedTime)
    TextView tvUsedTime;

    @BindView(R.id.rv_satellitesInfo)
    RecyclerView rvSatellitesInfo;

    private double trueLongitude;
    private double trueLatitude;

    private SvInfoAdapter svInfoAdapter;
    private List<GpsSatellite> gpsSatelliteList = new ArrayList<>();
    private GpsService mLocService;
    private boolean mServiceBound = false;
    private Location location;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ------------------------------");
            GpsService.LocalBinder binder = (GpsService.LocalBinder) service;
            MainActivity.this.mLocService = binder.getService();
            mServiceBound = true;
            Toast.makeText(MainActivity.this, "Service Connected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ------------------------------------");
            mServiceBound = false;
            mLocService = null;
            Toast.makeText(MainActivity.this, "Service Disconnected", Toast.LENGTH_SHORT).show();
        }
    };

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle;
            //开始定位
            if (intent.getAction().equals(GpsIntent.GPS_START_FIX)) {
                Log.d(TAG, "GPS_START_FIX------------------");
                bundle = intent.getExtras();
                tvSessionNo.setText(bundle.getInt(GpsIntent.CURRENT_SESSION) + "/" + bundle.getInt(GpsIntent.TOTAL_SESSION));
                tvFailureNo.setText(bundle.getInt(GpsIntent.CURRENT_RETRY) + "/" + bundle.getInt(GpsIntent.TOTAL_RETRY));
                tvTTFF.setText("");
                tvDistance.setText("");
                tvLongitude.setText("");
                tvLatitude.setText("");
                tvAltitude.setText("");
                tvUsedTime.setText("");
            }
            //获取TTFF值
            else if (intent.getAction().equals(GpsIntent.TIME_TO_FIRST_FIX)) {
                bundle = intent.getExtras();
                Log.d(TAG, "TIME_TO_FIRST_FIX--------------------");
                tvTTFF.setText(bundle.getInt(GpsIntent.TTFF)+"");
            }
            //更新GPS卫星信息
            else if (intent.getAction().equals(GpsIntent.GPS_SATELLITE_INFO)) {
                bundle = intent.getExtras();
                Log.d(TAG, "GPS_SATELLITE_INFO-------------------");
                SatelliteResult result =
                        (SatelliteResult) bundle.getSerializable(GpsIntent.SATELLITES);
                gpsSatelliteList.clear();
                for (GpsSatellite satellite : result.getGpsSatellites()) {
                    gpsSatelliteList.add(satellite);
                }
                Log.d(TAG, "SatelliteList--->" + gpsSatelliteList.toString());
                svInfoAdapter.notifyDataSetChanged();
            }
            //更新定位信息
            else if (intent.getAction().equals(GpsIntent.GPS_LOCATION_INFO)) {
                bundle = intent.getExtras();
                Log.d(TAG, "GPS_LOCATION_INFO-------------------");
                location = (Location) bundle.getParcelable(GpsIntent.LOCATION);
                tvLongitude.setText(location.getLongitude() + "");
                tvLatitude.setText(location.getLatitude() + "");
                tvAltitude.setText(location.getAltitude() + "");
                //更新距离
                tvDistance.setText(Utils.getDistance(location.getLongitude(),
                        location.getLatitude(),
                        trueLongitude, trueLatitude) + "");
                tvUsedTime.setText(Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            //定位任务完成
            else if (intent.getAction().equals(GpsIntent.GPS_TASK_FINISH)) {
                Log.d(TAG, "GPS_TASK_FINISH -------------------------------");
                btnStart.setEnabled(true);
                Toast.makeText(MainActivity.this, "测试已结束", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private boolean isReceiverRegistered = false;

    //注册广播监听器
    private void registerReceiver() {
        IntentFilter gpsBroadcastFilter = new IntentFilter();
        gpsBroadcastFilter.addAction(GpsIntent.GPS_START_FIX);
        gpsBroadcastFilter.addAction(GpsIntent.TIME_TO_FIRST_FIX);
        gpsBroadcastFilter.addAction(GpsIntent.GPS_SATELLITE_INFO);
        gpsBroadcastFilter.addAction(GpsIntent.GPS_LOCATION_INFO);
        gpsBroadcastFilter.addAction(GpsIntent.GPS_TASK_FINISH);
        registerReceiver(this.mReceiver, gpsBroadcastFilter);
        isReceiverRegistered = true;
    }

    //注销广播监听器
    private void unregisterReceiver() {
        MainActivity.this.unregisterReceiver(MainActivity.this.mReceiver);
        isReceiverRegistered = false;
    }


    @OnClick(R.id.btn_start)
    void start() {
        //判断输入参数齐全
        if (etIntervalTime.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_milliseconds_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (etLatitude.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_latitude_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etLongitude.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_longitude_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etSessionTimes.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_times_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etOvertime.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_overtime_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etRetryTimes.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_retry_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d(TAG, "start: ---------------------------------");
        //循环次数
        int times = Integer.parseInt(etSessionTimes.getText().toString().trim());
        //间隔时间
        int interval_time = Integer.parseInt(etIntervalTime.getText().toString().trim());
        //超时时间
        int overtime = Integer.parseInt(etOvertime.getText().toString().trim());
        //重试次数
        int retry_times = Integer.parseInt(etRetryTimes.getText().toString().trim());
        //存储到SharedPreferences
        SpUtils.setTestTimes(this, times + "");
        SpUtils.setIntervalTime(this, interval_time + "");
        SpUtils.setOverTime(this, overtime + "");
        SpUtils.setRetryTimes(this, retry_times + "");

        //存储输入的经纬度
        String inputLongitude = etLongitude.getText().toString().trim();
        String inputLatitude = etLatitude.getText().toString().trim();
        SpUtils.setInputLongitude(this, inputLongitude);
        SpUtils.setInputLatitude(this, inputLatitude);

        trueLongitude = Double.parseDouble(inputLongitude);
        trueLatitude = Double.parseDouble(inputLatitude);

        btnStart.setEnabled(false);

        boolean isHot = SpUtils.getStartWay(this).equals(SpUtils.HOT_START);
        mLocService.startTask(times, interval_time, overtime, retry_times,
                isHot);

    }

    @OnClick(R.id.btn_stop)
    void stop() {
        mLocService.stopTask();
        btnStart.setEnabled(true);
        Toast.makeText(this, "测试已停止", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initListener();
        if (!isReceiverRegistered) {
            registerReceiver();
        }
        initData();
        if (!mServiceBound) {
            bindService();
        }
    }

    private void initData() {
        etSessionTimes.setText(SpUtils.getTestTimes(this));
        etIntervalTime.setText(SpUtils.getIntervalTime(this));
        etOvertime.setText(SpUtils.getOverTime(this));
        etRetryTimes.setText(SpUtils.getRetrytimes(this));
    }

    private void initListener() {
        rgStartWay.setOnCheckedChangeListener(new SmoothRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SmoothRadioGroup smoothRadioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.cold_start:
                        SpUtils.setStartWay(MainActivity.this, SpUtils.COLD_START);
                        break;
                    case R.id.hot_start:
                        SpUtils.setStartWay(MainActivity.this, SpUtils.HOT_START);
                        break;
                }
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        rvSatellitesInfo.setLayoutManager(linearLayoutManager);
        //设置为垂直布局，这也是默认的
        linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        if (svInfoAdapter == null) {
            svInfoAdapter = new SvInfoAdapter(gpsSatelliteList);
        }
        rvSatellitesInfo.setAdapter(svInfoAdapter);
        //设置分隔线
        rvSatellitesInfo.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        //设置增加或删除条目的动画
        rvSatellitesInfo.setItemAnimator(new DefaultItemAnimator());

    }

    private void bindService() {
        Intent intent = new Intent(this, GpsService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isReceiverRegistered) {
            unregisterReceiver();
        }
        if (mServiceBound) {
            unbindService(mServiceConnection);
            mServiceBound = false;
        }

    }


}
